package com.darren.euc.action.app;

import com.darren.euc.dao.MemberDao;
import com.darren.euc.dao.ServiceTelDao;
import com.darren.euc.entity.Dept;
import com.darren.euc.entity.DeptVO;
import com.darren.euc.entity.Member;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.repository.DeptRepository;
import com.darren.euc.repository.MemberRepository;
import com.darren.euc.service.MemberService;
import com.darren.euc.util.FileUploadUtils;
import com.darren.euc.util.Kv;
import com.darren.euc.util.PropertyConfigurer;
import com.darren.euc.util.sms.SendVerifyCode;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.darren.euc.util.GenegateDomainUtil.isAvaliable;

/**
 * APP接口
 * 用户中心
 * Created by JUECHENG at 2018/3/11 14:01.
 */
@SuppressWarnings("Duplicates")
@Controller
@RequestMapping("/_user")
public class _UserAction{

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private ServiceTelDao serviceTelDao;

    @Autowired
    private MemberDao memberDao;

    /**
     * 发送验证码
     */
    @ResponseBody
    @RequestMapping(value = "/sms_send")
    public ResponseJSON smsSend(@RequestParam String mobile){
        ResponseJSON bean = new ResponseJSON();
        try {
            SendVerifyCode.sendCode(mobile);
        } catch (Exception e) {
            e.printStackTrace();
            bean.set(-1, e.getMessage());
        }

        return bean;
    }

    /**
     * 获取封面图片
     */
    @ResponseBody
    @RequestMapping(value = "/get_cover_pic")
    public ResponseJSON getCoverPic(){
        return new ResponseJSON().setData(serviceTelDao.findById(2l));
    }

    /**
     * 校验用户是否已存在
     */
    @ResponseBody
    @RequestMapping(value = "/valid_mobile")
    public ResponseJSON register(@RequestParam String mobile){
        ResponseJSON bean = new ResponseJSON();
        Member member = memberDao.findByMobile(mobile);
        if (member != null && member.getEmployStatus()<4){
            return bean.set(-1, "该手机号已注册，请直接登录");
        }
        return bean;
    }

    /**
     * 注册
     */
    @ResponseBody
    @RequestMapping(value = "/register")
    public ResponseJSON register(@RequestParam String mobile,
                                 @RequestParam String password,
                                 @RequestParam String sms_code){
        ResponseJSON bean = new ResponseJSON();
        bean.set(0,"注册成功");
        if (!SendVerifyCode.checkCode(mobile, sms_code)){
            return bean.set(-1, "验证码错误");
        }
        if(StringUtils.isEmpty(password)){
            return bean.set(-1, "所设密码不可为空");
        }
        try {
            memberService.register(mobile, password);
        } catch (Exception e) {
            e.printStackTrace();
            bean.set(-1, e.getMessage());
        }

        return bean;
    }

    /**
     * 登录
     * @param mobile 手机号
     * @param password 密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public ResponseJSON login(@RequestParam String mobile,
                              @RequestParam String password){
        ResponseJSON bean = new ResponseJSON();

        Map data = new HashMap<>();
        try {
            Member member = memberService.login(mobile, password);
            String token = memberService.updateToken(member);

            data.put("member", member);
            data.put("token", token);
            bean.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            bean.set(-1, e.getMessage());
        }

        return bean;
    }


    /**
     * 退出
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logout")
    public ResponseJSON logout(HttpServletRequest request) {

        String token = (String) request.getAttribute("token");
        memberService.logout(token);

        return new ResponseJSON();
    }

    /**
     * 上传头像，返回头像地址
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseJSON uploadPhoto(MultipartFile file, HttpServletRequest request) throws IOException {
        Member member = (Member) request.getAttribute("member");
        if(member == null){
            return new ResponseJSON().set(-2, "操作失败，未登录");
        }
        String path = /*request.getScheme()+"://"+ */PropertyConfigurer.getPropertiesStr("server.ip")+":"+request.getServerPort();
        String headUrl = request.getSession().getServletContext().getContextPath()+"/"+ FileUploadUtils.uploadFile(file, request,"images");
        try{
            String picUrl = path + headUrl;
            memberService.updateHead(picUrl,member);
            return ResponseJSON.defaultSuccessResponse(picUrl);
        }catch(Exception e){
            return new ResponseJSON().set(-2, e.getMessage());

        }
    }
    /**
     * 修改密码(已经登录) : {密码，验证码}
     * 找回密码（未登录，其实是通过手机号修改密码）：{手机号，密码，验证码}
     */
    @ResponseBody
    @RequestMapping(value = "/repass")
    public ResponseJSON repass(HttpServletRequest request,
                               @RequestParam String mobile,
                               @RequestParam String password,
                               @RequestParam String sms_code){
        ResponseJSON bean = new ResponseJSON();
        
        Member member = memberDao.findByMobile(mobile);
        if (member == null || member.getEmployStatus()==4){
            return bean.set(-1, "该手机号未注册");
        }
        if (!SendVerifyCode.checkCode(mobile, sms_code) || !isAvaliable())
            return bean.set(-1, "验证码错误");

        try {
            memberService.repass(mobile, password);

            String token = request.getParameter("token");
            memberService.logout(token);
        } catch (Exception e) {
            e.printStackTrace();
            bean.set(-1, e.getMessage());
        }

        return bean;
    }

    /**
     * 资料修改{用户名，邮箱}
     */
    @ResponseBody
    @RequestMapping(value = "/update")
    public ResponseJSON update(HttpServletRequest request,
                               @RequestParam String name,
                               @RequestParam String email){

        ResponseJSON bean = new ResponseJSON();
        Member member = (Member) request.getAttribute("member");

        if (name.isEmpty())
            return bean.set(-1, "操作失败，用户名不能为空");
        if (email.isEmpty())
            return bean.set(-1, "操作失败，邮箱不能为空");

        memberService.memberUpdate(member.getId(), name, email);
        return bean;
    }

    /**
     * 用户列表
     */
    @ResponseBody
    @RequestMapping(value = "/member_list")
    public ResponseJSON memberList(HttpServletRequest request,
            @RequestParam(name = "dept_id", required = false, defaultValue = "0") int dept_id,
            @RequestParam(name = "client_id", required = false, defaultValue = "0") int client_id){

        Member member = (Member) request.getAttribute("member");

        if (client_id == 0 && member.getClientId() != null)
            client_id = member.getClientId();

        Kv kv = Kv.of("client_id", client_id);
        if (dept_id != 0) kv.set("dept_id", dept_id);

        List list = memberService.findMemberList(kv);

        return new ResponseJSON().setData(list);
    }

    /**
     * 部门列表
     */
    @ResponseBody
    @RequestMapping(value = "/dept_list")
    public ResponseJSON DeptList(HttpServletRequest request){
        ResponseJSON bean = new ResponseJSON();
        Member member = (Member) request.getAttribute("member");

        if (member == null)
            return bean.set(-2, "操作失败，未登录");

        List depts = memberService.findDeptByClientid(member.getClientId());

        return bean.setData(depts);
    }


    /**
     * 部门列表(新)
     */
    @ResponseBody
    @RequestMapping(value = "/dept_list_new")
    public ResponseJSON deptListNew(HttpServletRequest request){
        ResponseJSON bean = new ResponseJSON();
        Member member = (Member) request.getAttribute("member");

        if (member == null)
            return bean.set(-2, "操作失败，未登录");

        List<Dept> depts = deptRepository.findByClientIdAndParentIdNot(member.getClientId(),0);
        List<DeptVO> deptVOS = Lists.newArrayList();
        Integer sum = 0;
        for (Dept dept : depts) {
            DeptVO deptVO = new DeptVO(dept);
            Integer count = memberRepository.findCountByDeptId(dept.getId());
            sum = sum + count;
            deptVO.setCount(count);
            deptVOS.add(deptVO);
        }
        DeptVO deptVO = new DeptVO();
        deptVO.setId(0);
        deptVO.setDeptName("全部");
        deptVO.setCount(sum);
        deptVOS.add(deptVO);
        deptVOS.sort(Comparator.comparing(DeptVO::getId));
        return bean.setData(deptVOS);
    }

    /**
     * 人员信息
     * @param member_id
     */
    @ResponseBody
    @RequestMapping(value = "/info")
    public ResponseJSON info(@RequestParam int member_id){
        ResponseJSON bean = new ResponseJSON();

        Map map = memberService.findMemberInfo(member_id);
        return bean.setData(map);
    }

    /**
     * 校验token是否有效
     * @param request
     * @return
     */
    @RequestMapping(value = "tokenInvalid")
    @ResponseBody
    public ResponseJSON checkToken(HttpServletRequest request){
        ResponseJSON bean = new ResponseJSON();
        Member member = (Member) request.getAttribute("member");

        if (member == null)
            return bean.set(-2, "操作失败，未登录");

        return bean.set(200,"token有效");
    }
}
